define(["jquery", "easy-admin"], function ($, ea) {

    var init = {
        table_elem: '#currentTable',
        table_render_id: 'currentTableRenderId',
        index_url: 'insurance.report/index',
        add_url: 'insurance.report/add',
        edit_url: 'insurance.report/edit',
        delete_url: 'insurance.report/delete',
        export_url: 'insurance.report/export',
        modify_url: 'insurance.report/modify',
        report_url: 'insurance.report/report',


    };

    return {

        index: function () {
            ea.table.render({
                init: init,
                toolbar: ['refresh',
                    [
                        {
                            text: '导出费用报表',
                            url: init.report_url,
                            method: 'none',
                            auth: '',
                            class: 'layui-btn layui-btn-normal layui-btn-sm',
                            icon: '',
                            extend: 'lay-active="report" data-url="'+init.report_url+'" data-width="90%" data-height="95%"',
                        },
                    ], 
                ],
                cols: [[
                    {type: "checkbox"},
                    {field: 'type', minWidth: 80, title: '保单类型', search: false, templet: function(d) {
                        switch(d.type) {
                            case 1: return '商业';
                            case 2: return '驾乘';
                            case 0: return '交强';
                        }
                    }},
                    {field: 'agent', minWidth: 80, title: '代理人'},
                    {field: 'user.insurer', minWidth: 80, title: '投保人', search: false},
                    {field: 'user.carno', minWidth: 80, title: '车牌号', search: false},
                    {field: 'cost', minWidth: 80, title: '保费', search: false, edit: 'text'},
                    {field: 'report.amount_me', minWidth: 80, title: '代理费ME', search: false, edit: 'text', templet: function(d){
                        return d.report.amount_me || '';
                    }},
                    {field: 'report.red_point', minWidth: 80, title: '代理点ME', search: false, templet: function(d){
                        return d.report.red_point_me || '';
                    }},
                    {field: 'report.amount', minWidth: 80, title: '代理费', search: false, edit: 'text', templet: function(d){
                        return d.report.amount || '';
                    }},
                    {field: 'report.red_point', minWidth: 80, title: '代理点', search: false, templet: function(d){
                        return d.report.red_point || '';
                    }},
                    {field: 'report.scharge', minWidth: 80, title: '手续费', search: false, edit: 'text', templet: function(d){
                        return d.report.scharge || '';
                    }},
                    {field: 'report.amount_not', minWidth: 80, title: '未结费', search: false, templet: function(d){
                        return Math.round((d.report.amount_me - d.report.scharge) * 100) / 100 || '';
                    }},
                    {field: 'create_at', minWidth: 80, title: '出单时间', search: 'range'},
                    {field: 'is_billpay', minWidth: 80, title: '结费状态', search: 'select', selectList: {0: '未结', 1: '已结'}, templet: function (d) {
                        return d.is_billpay === 1 ? '<span style="color: red">已结</span>' : '未结';
                    }},
                    {field: 'type', minWidth: 80, title: '维度', search: false, templet: function(d) {
                        var text = '';
                        if (!d.types) return text;
                        for (let item of d.types) {
                            switch(item.type) {
                                case 1: text += '商'; break;
                                case 2: text += '驾'; break;
                                case 0: text += '交'; break;
                            }
                            if (item != d.types[d.types.length - 1]) text += '+';
                        }
                        return text;
                    }},
                ]],
                done: function () {
                    // excel导出
                    layui.util.event('lay-active', {
                        report: function(data) {
                            console.log(data)
                            var tableId = $(this).attr('data-table-report'),
                                url = $(this).attr('data-url');

                            let par = $("#searchFieldset_" + init.table_render_id).find('form').serialize();
                            let parArr = par.split('&')
                            var formatFilter = {}, formatOp = {};
                            [formatData] = parArr.map((arr) => {
                                [key, val] = arr.split('=');
                                if (val !== '') {
                                    formatFilter[key] = val;
                                    var op = $('#c-' + key).attr('data-search-op');
                                    op = op || '%*%';
                                    formatOp[key] = op;
                                }
                                return {formatFilter, formatOp};
                            })
                            console.log(formatData)
                            let schPar = 'filter=' + JSON.stringify(formatData.formatFilter) + '&' + 'op=' + JSON.stringify(formatData.formatOp);
                            url = (url.includes('?')) ? url + '&' + schPar : url + '?' + schPar;
                            var index = ea.msg.confirm('根据查询进行导出，确定导出？', function () {
                                window.location = ea.url(url);
                                layer.close(index);
                            });
                        }
                    });
                }
            });

            ea.listen();
        },
        add: function () {
            layui.util.on({
                AiOptimization: function (data) {
                    let layOn = $(data).attr('lay-on')
                    $(data).attr('lay-on', layOn + 'Loading')
                    aiOptimization(data)
                },
            });
            
            ea.listen();
        },
        edit: function () {
            layui.util.on({
                AiOptimization: function (data) {
                    let layOn = $(data).attr('lay-on')
                    $(data).attr('lay-on', layOn + 'Loading')
                    aiOptimization(data)
                },
            })

            ea.listen();
        },
        stock: function () {
            ea.listen();
        },
        recycle: function () {
            init.index_url = init.recycle_url;
            ea.table.render({
                init: init,
                toolbar: ['refresh',
                    [{
                        class: 'layui-btn layui-btn-sm',
                        method: 'get',
                        field: 'id',
                        icon: 'fa fa-refresh',
                        text: '全部恢复',
                        title: '确定恢复？',
                        auth: 'recycle',
                        url: init.recycle_url + '?type=restore',
                        checkbox: true
                    }, {
                        class: 'layui-btn layui-btn-danger layui-btn-sm',
                        method: 'get',
                        field: 'id',
                        icon: 'fa fa-delete',
                        text: '彻底删除',
                        title: '确定彻底删除？',
                        auth: 'recycle',
                        url: init.recycle_url + '?type=delete',
                        checkbox: true
                    }], 'export',
                ],
                cols: [[
                    {type: "checkbox"},
                    {field: 'id', width: 80, title: 'ID', searchOp: '='},
                    {field: 'sort', width: 80, title: '排序', edit: 'text'},
                    {field: 'cate_id', minWidth: 80, title: '商品分类', search: 'select', selectList: cateSelects, laySearch: true},
                    {field: 'title', minWidth: 80, title: '商品名称'},
                    {field: 'logo', minWidth: 80, title: '分类图片', search: false, templet: ea.table.image},
                    {field: 'status', title: '状态', width: 85, selectList: {0: '禁用', 1: '启用'}},
                    // 演示多选，实际数据库并无 status2 字段，搜索后会报错
                    {
                        field: 'status2', title: '演示多选', width: 105, search: 'xmSelect', selectList: {1: '模拟选项1', 2: '模拟选项2', 3: '模拟选项3', 4: '模拟选项4', 5: '模拟选项5'},
                        searchOp: 'in', templet: function (res) {
                            // 根据自己实际项目进行输出
                            return res?.status2 || '模拟数据'
                        }
                    },
                    {field: 'create_time', minWidth: 80, title: '创建时间', search: 'range'},
                    {field: 'delete_time', minWidth: 80, title: '删除时间', search: 'range'},
                    {
                        width: 250,
                        title: '操作',
                        templet: ea.table.tool,
                        operat: [
                            [{
                                title: '确认恢复？',
                                text: '恢复数据',
                                filed: 'id',
                                url: init.recycle_url + '?type=restore',
                                method: 'get',
                                auth: 'recycle',
                                class: 'layui-btn layui-btn-xs layui-btn-success',
                            }, {
                                title: '想好了吗？',
                                text: '彻底删除',
                                filed: 'id',
                                method: 'get',
                                url: init.recycle_url + '?type=delete',
                                auth: 'recycle',
                                class: 'layui-btn layui-btn-xs layui-btn-normal layui-bg-red',
                            }]]
                    }
                ]],
            });
            ea.listen();
        },

        upload: function () {
            ea.listen();
        }
    };

    function aiOptimization(data) {
        let layOn = $(data).attr('lay-on')
        let title = $('input[name="title"]').val()

        // 告诉AI 你需要做什么
        let message = `优化这个标题 ${title}`

        if ($.trim(title) === '') {
            ea.msg.error('标题不能为空', function () {
                $(data).attr('lay-on', layOn.split('Loading')[0])
            })
            return false
        }
        let url = ea.url('insurance.pollicy/aiOptimization')
        ea.request.post({url: url, data: {message: message}}, function (res) {
            let content = res.data?.choices[0]?.message?.content
            // stream 为true 时，AI 内容会逐字输出
            let stream = true
            ea.ai.chat(content, {stream: stream}, function () {
                $(data).attr('lay-on', layOn.split('Loading')[0])
            })
        }, function (error) {
            ea.msg.error(error.msg, function () {
                $(data).attr('lay-on', layOn.split('Loading')[0])
            })
        })
    }
});